//
//  UserSetUpViewController.m
//  CheekiOS
//
//  Created by mac on 2017/6/22.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "UserSetUpViewController.h"
#import "UserSetUpCell.h"
//登录页
#import "GifloginViewController.h"
//弹框
#import "AlertViewExtension.h"
//账户与安全
#import "UserAccountSecurityController.h"
//黑名单
#import "UserBlackListController.h"
//处罚名单
#import "UserPunishmentListController.h"
//关于我们
#import "UserAboutUsController.h"
//帮助与反馈
#import "UserFeedBackController.h"
@interface UserSetUpViewController ()<UITableViewDelegate, UITableViewDataSource,alertviewExtensionDelegate>

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSString *cachSizeStr;
@property (nonatomic, strong)AlertViewExtension *alert;
@property (nonatomic, strong)NSString *cacheLogoutStr;
@end

@implementation UserSetUpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _cacheLogoutStr = @"";
    self.cachSizeStr =[self sizeFromTotalSize:[self folderSizeAtPath]];

    [self setNavgationBarHiddenNo];
    self.title = @"设置";
    
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight-49) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 7;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UserSetUpCell *cell = [UserSetUpCell cellWithTableView:tableView indexPath:indexPath];
    
    cell.cacheLab.text = _cachSizeStr;
    
    return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0 || indexPath.row == 3 || indexPath.row == 6) {
        return 75;
    }else{
        return 55;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.row) {
        case 0:{
            NSLog(@"账号与安全");
            UserAccountSecurityController *vc = [[UserAccountSecurityController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        case 1:
        {
            NSLog(@"黑名单");
            UserBlackListController *vc = [[UserBlackListController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        break;
        case 2:{
            NSLog(@"处罚名单");
            UserPunishmentListController *vc = [[UserPunishmentListController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        break;
        case 3:{
            NSLog(@"清除缓存");
            _cacheLogoutStr = @"0";
            [self logOutclearCaches:_cacheLogoutStr];
        }
        break;
        case 4:{
            NSLog(@"关于我们")
            UserAboutUsController *vc = [[UserAboutUsController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 5:{
            NSLog(@"帮助与反馈");
            UserFeedBackController *vc = [[UserFeedBackController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 6:{
            NSLog(@"退出");
            _cacheLogoutStr = @"1";
            [self logOutclearCaches:_cacheLogoutStr];
            
        }
            break;
        default:
            break;
    }
    
}

#pragma =====================mark--logOut========= 清除缓存=============
-(void)logOutclearCaches:(NSString *)str{
    
    self.alert =[[AlertViewExtension alloc]initWithFrame:CGRectMake(0, 0,KScreenWidth, KScreenHeight)];
    self.alert.delegate=self;
    [self.alert setbackviewframeWidth:KScreenWidth-50 Andheight:110];
    if ([str isEqualToString:@"1"]) {
        [self.alert settipeTitleStr:@"确认退出登录？" Andfont:14];
        
    }else{
        [self.alert settipeTitleStr:@"确认清除缓存？" Andfont:14];
        
    }
    [self.view addSubview:self.alert];
    
    
}

//弹框回调
-(void)clickBtnSelector:(UIButton *)btn
{
    if (btn.tag == 0) {
        if ([_cacheLogoutStr isEqualToString:@"0"]) {
            WEAKSELF
            NSFileManager *fileManger = [NSFileManager defaultManager];
            NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
            
            if ([fileManger fileExistsAtPath:path]) {
                NSArray *fileArray = [fileManger subpathsAtPath:path];
                [fileArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSString *absolutePath = [path stringByAppendingPathComponent:obj];
                    [fileManger removeItemAtPath:absolutePath error:nil];
                }];
            }
            [[SDImageCache sharedImageCache] cleanDiskWithCompletionBlock:^{
                [SVProgressHUD showSuccessWithStatus:@"清除缓存成功"];
                weakSelf.cachSizeStr =[weakSelf sizeFromTotalSize:[weakSelf folderSizeAtPath]];
                [weakSelf.tableView reloadData];
            }];

        }else{
            [defaults setValue:@"" forKey:@"mobile"];
            [defaults setValue:@"" forKey:@"password"];
            [defaults setValue:@"" forKey:@"thirdNO"];
            [defaults setValue:@"" forKey:@"thirdType"];
            [defaults setObject:@"0" forKey:@"isFirstComeIn"];
            [defaults setValue:@"" forKey:@"cheekVodepSig"];

            [defaults synchronize];
            [[RCIM sharedRCIM] logout];
            [[ILiveLoginManager getInstance] iLiveLogout:^{
                NSLog(@"腾讯云退出等路");
            } failed:^(NSString *module, int errId, NSString *errMsg) {
                
            }];
            
            
            
            GifloginViewController *loginVC = [[GifloginViewController alloc] init];
            //Root动画
            typedef void (^Animation)(void);
            
            loginVC.modalTransitionStyle =UIModalTransitionStyleFlipHorizontal;
            
            Animation animation = ^{
                
                BOOL oldState = [UIView areAnimationsEnabled];
                
                [UIView setAnimationsEnabled:NO];
                UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
                [UIApplication sharedApplication].keyWindow.rootViewController  = nav;
                
                
                
                [UIView setAnimationsEnabled:oldState];
                
            };
            
            [UIView transitionWithView:[UIApplication sharedApplication].keyWindow
             
                              duration:0.7f
             
                               options:UIViewAnimationOptionTransitionFlipFromLeft
             
                            animations:animation
             
                            completion:nil];
            
        }
        [self.alert removeFromSuperview];


       
            
    }else{
        [self.alert removeFromSuperview];
    }
}


#pragma mark - =================获取缓存大小================
-(float)folderSizeAtPath{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSString *cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    //NSLog(@"path = %@",cachePath);
    long long folderSize=0;
    if ([fileManager fileExistsAtPath:cachePath])
    {
        NSArray *childerFiles=[fileManager subpathsAtPath:cachePath];
        for (NSString *fileName in childerFiles)
        {
            NSString *fileAbsolutePath=[cachePath stringByAppendingPathComponent:fileName];
            long long size=[self fileSizeAtPath:fileAbsolutePath];
            folderSize += size;
            //NSLog(@"fileAbsolutePath=%@",fileAbsolutePath);
        }
        //SDWebImage框架自身计算缓存的实现
        folderSize+=[[SDImageCache sharedImageCache] getSize];
        return folderSize*0.6;
    }
    return 0;
}

-(long long)fileSizeAtPath:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path]){
        long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size;
    }
    return 0;
}

-(NSString *)sizeFromTotalSize:(CGFloat)totalSize{
    if(totalSize<1000){
        return [NSString stringWithFormat:@"%ldB",(long)totalSize];
    }
    else{
        if(totalSize<1000*1000){
            return [NSString stringWithFormat:@"%.2fKB",totalSize*1.0/1024ll];
        }
        else{
            if(totalSize<1000*1000*1000){
                return [NSString stringWithFormat:@"%.2fMB",(totalSize*1.0/1024ll/1024ll)];
            }
            else{
                return [NSString stringWithFormat:@"%.2fGB",(totalSize*1.0/1024/1024/1024)];
            }
        }
    }
}

@end
